import struct
from typing import List

# 通信协议类
class BinaryProtocol:
    FORMAT_HEADER = '>BBH'  # 大端序：uint8_t, uint8_t, uint16_t
    HEADER_SIZE = struct.calcsize(FORMAT_HEADER)

    def __init__(self, type: int, reserved: int, payload_size: int, payload: bytes):
        self.type = type
        self.reserved = reserved
        self.payload_size = payload_size
        self.payload = payload
    
    @classmethod
    def from_bytes(cls, data: bytes) -> 'BinaryProtocol':
        header = data[:cls.HEADER_SIZE]
        payload = data[cls.HEADER_SIZE:]
        
        type, reserved, payload_size = struct.unpack(cls.FORMAT_HEADER, header)
        return cls(type, reserved, payload_size, payload[:payload_size])

    def to_bytes(self) -> bytes:
        header = struct.pack(self.FORMAT_HEADER, self.type, self.reserved, self.payload_size)
        return header + self.payload[:self.payload_size]

    def __str__(self):
        return (f"BinaryProtocol(type={self.type}, reserved={self.reserved}, "
                f"payload_size={self.payload_size}, payload={self.payload[:10]}...)")